package toOffer;

/**
 * @author YuanAo
 * @date 2024/6/28 15:12
 * @description 训练计划IV
 */

import java.util.Objects;

/**
 * 题目：
 * 给定两个以 有序链表 形式记录的训练计划 l1、l2，分别记录了两套核心肌群训练项目编号，请合并这两个训练计划，按训练项目编号 升序 记录于链表并返回。
 * 注意：新链表是通过拼接给定的两个链表的所有节点组成的。
 * 示例 1：
 * 输入：l1 = [1,2,4], l2 = [1,3,4]
 * 输出：[1,1,2,3,4,4]
 * 示例 2：
 * 输入：l1 = [], l2 = []
 * 输出：[]
 * 示例 3：
 * <p>
 * 输入：l1 = [], l2 = [0]
 * 输出：[0]
 */
public class LCR142 {
    public static void main(String[] args) {
        int[] ints1 = {};
        // 初始化
        ListNode l1 = new ListNode();
        for (int i = ints1.length - 1; i >= 0; i--) {
            if (i == ints1.length - 1) {
                l1 = new ListNode(ints1[i]);
            } else {
                l1 = new ListNode(ints1[i], l1);
            }
        }

        int[] ints2 = {1};
        // 初始化
        ListNode l2 = new ListNode();
        for (int i = ints2.length - 1; i >= 0; i--) {
            if (i == ints2.length - 1) {
                l2 = new ListNode(ints2[i]);
            } else {
                l2 = new ListNode(ints2[i], l2);
            }
        }

        ListNode ln = trainningPlan(l1, l2);
        while (Objects.nonNull(ln)) {
            System.out.print(ln.getVal() + " ");
            ln = ln.next;
        }
    }

    /**
     *
     * @param l1
     * @param l2
     * @return
     */
    public static ListNode trainningPlan(ListNode l1, ListNode l2) {
        if(l1 == null) return l2;
        if(l2 == null) return l1;

        ListNode head = new ListNode();
        ListNode tn = head;

        while (l1 != null && l2 != null){
            if (l1.val < l2.val){
                tn.next = l1;
                l1 = l1.next;
            }else {
                tn.next = l2;
                l2 = l2.next;
            }
            tn = tn.next;

            if (l1 != null){
                tn.next = l1;
            }else{
                tn.next = l2;
            }
        }

        return head.next;
    }

    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }

        public int getVal() {
            return val;
        }

        public void setVal(int val) {
            this.val = val;
        }

        public ListNode getNext() {
            return next;
        }

        public void setNext(ListNode next) {
            this.next = next;
        }
    }
}
